package com.zhuoyue.elmt.api;

import com.eit.eitsite.common.config.Global;
import com.eit.eitsite.common.persistence.Page;
import com.eit.eitsite.common.utils.CookieUtils;
import com.eit.eitsite.common.utils.DateUtils;
import com.eit.eitsite.common.utils.SpringContextHolder;
import com.eit.eitsite.common.utils.StringUtils;
import com.eit.eitsite.common.web.BaseController;
import com.eit.eitsite.modules.sys.entity.Dict;
import com.eit.eitsite.modules.sys.entity.User;
import com.eit.eitsite.modules.sys.security.FormAuthenticationFilter;
import com.eit.eitsite.modules.sys.security.SystemAuthorizingRealm;
import com.eit.eitsite.modules.sys.security.UsernamePasswordToken;
import com.eit.eitsite.modules.sys.service.DictService;
import com.eit.eitsite.modules.sys.utils.DictUtils;
import com.eit.eitsite.modules.sys.utils.UserUtils;
import com.google.common.collect.Lists;
import com.zhuoyue.elmt.Constants;
import com.zhuoyue.elmt.SmsSender;
import com.zhuoyue.elmt.data.ResultData;
import com.zhuoyue.elmt.entity.*;
import com.zhuoyue.elmt.service.*;
import net.sf.jasperreports.engine.JasperRunManager;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping(value = "${frontPath}/sydwfront")
public class SydwFrontController extends BaseController {

    public static final String GG_SYDW_SESSION = "GG_SYDW_SESSION";

    @Autowired
    private GgSydwService ggSydwService;

    @Autowired
    private DeviceParametersService deviceParametersService;

    @Autowired
    private MaintenanceRecordSzService maintenanceRecordSzService;

    @Autowired
    private FailureReportService failureReportService;

    @Autowired
    private DictService dictService;

    @Autowired
    private WbInspectRecordService wbInspectRecordService;

    @Autowired
    private WbInsuranceRecordService wbInsuranceRecordService;

    @RequestMapping(value = "sendSms")
    @ResponseBody
    public String sendSms(String mobile, HttpServletRequest request, HttpServletResponse response) {
        ResultData resultData = new ResultData();
        try {
            resultData.setCode("SUCC");
            resultData.setMessage("短信验证码发送成功");

            String smsOverTime = Global.getConfig("sms.over.time");
            String code = SmsSender.genRandomStr();
            String sendContent = MessageFormat.format(Global.getConfig("sms.content"), code);

            String startDate = DateUtils.getDateTime();
            logger.info("短信内容：" + sendContent + " 发送时间：" + startDate);

            request.getSession().setAttribute(Constants.SMS.STARTDATE, startDate);
            request.getSession().setAttribute(Constants.SMS.CODE, code);
        } catch (Exception e) {
            resultData.setCode("FAIL");
            resultData.setMessage("短信发送异常！");
            e.printStackTrace();
        }
        return super.renderString(response, resultData);
    }


    @RequestMapping(value = "sydwlogin")
    public String sydwlogin(HttpServletRequest request, HttpServletResponse response, User user, String username, String password, String orgtype, Model model) {
        try {
            GgSydw qryGgSydw = new GgSydw();
            qryGgSydw.setZzjqdm(username);
            qryGgSydw.setDlmm(password);
            GgSydw ggSydw = ggSydwService.getByCode(qryGgSydw);

            String message = "";

            if (StringUtils.isEmpty(username)) {
                message = "用户名为空";
                model.addAttribute(Constants.MESSAGE.SMS_MESSAGE, message);

                return "modules/sys/sysLogin";
            }

            if(ggSydw == null) {
                message = "没有找到对应的使用单位或密码错误";
                model.addAttribute(Constants.MESSAGE.SMS_MESSAGE, message);
                model.addAttribute("orgtype", orgtype);
                model.addAttribute("username", username);

                return "modules/sys/sysLogin";
            } else {
                request.getSession().setAttribute(GG_SYDW_SESSION, ggSydw);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        //        // 校验短信
        //        String code = "";
        //        String startDate = "";
        //        if (request.getSession().getAttribute(Constants.SMS.CODE) != null) {
        //            code = (String) request.getSession().getAttribute(Constants.SMS.CODE);
        //        }
        //        if (request.getSession().getAttribute(Constants.SMS.STARTDATE) != null) {
        //            startDate = (String) request.getSession().getAttribute(Constants.SMS.STARTDATE);
        //        }
        //        String message = "";
        //
        //        if (StringUtils.isEmpty(code) || StringUtils.isEmpty(startDate)) {
        //            message = "验证码已过期";
        //            model.addAttribute(Constants.MESSAGE.SMS_MESSAGE, message);
        //
        //            return "modules/sys/sysLogin";
        //        }
        //
        //        String smscode = user.getSmscode();
        //        try {
        //            int smsOverTime = Integer.parseInt(Global.getConfig("sms.over.time"));
        //
        //            int result = DateUtils.calculateTime(DateUtils.parseDate(startDate, "yyyy-MM-dd HH:mm:ss"));
        //
        //            if (result > smsOverTime) {
        //                message = "验证码已过期";
        //                model.addAttribute(Constants.MESSAGE.SMS_MESSAGE, message);
        //
        //                return "modules/sys/sysLogin";
        //            } else {
        //                if (smscode.equals(code)) {
        //                } else {
        //                    message = "请输入正确的验证码";
        //                    model.addAttribute(Constants.MESSAGE.SMS_MESSAGE, message);
        //
        //                    return "modules/sys/sysLogin";
        //                }
        //            }
        //
        //            // 查找使用单位
        //            GgSydw qryGgSydw = new GgSydw();
        //            qryGgSydw.setLxrdh(username);
        //            GgSydw ggSydw = ggSydwService.getByMobile(qryGgSydw);
        //
        //            if (ggSydw != null) {
        //                // 模拟登录
        //                // 使用单位权限 设备查询 电梯档案 打印维保记录PDF
        //                Subject subject = SecurityUtils.getSubject();
        //                String password = "Admin0.123";
        //                UsernamePasswordToken token = new UsernamePasswordToken("sydw", password.toCharArray(), false, "", "", false, "", "");
        //                subject.login(token);//登录
        //
        //                User shiroUser = UserUtils.getUser();
        //                shiroUser.setName(ggSydw.getDwmc());
        //                shiroUser.setLoginName(ggSydw.getZzjqdm());
        //            } else {
        //                message = "没有找到对应的使用单位";
        //                model.addAttribute(Constants.MESSAGE.SMS_MESSAGE, message);
        //
        //                return "modules/sys/sysLogin";
        //            }
        //        } catch (Exception e) {
        //            e.printStackTrace();
        //        }
        //
        return "zhuoyue/sydw/sysIndexSydw";
    }

    @RequestMapping(value = "deviceList")
    public String deviceList(DeviceParameters deviceParameters, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!isSydwLogin(request)) {
            return "modules/sys/sysLogin";
        }
        GgSydw ggSydw = (GgSydw) request.getSession().getAttribute(GG_SYDW_SESSION);
        deviceParameters.setSydwdm(ggSydw.getZzjqdm());
        deviceParameters.setRemark("all");
        Page<DeviceParameters> page = deviceParametersService.findPage(new Page<DeviceParameters>(request, response), deviceParameters);
        model.addAttribute("page", page);
        return "zhuoyue/sydw/deviceParametersList";
    }

    @RequestMapping(value = "deviceForm")
    public String deviceForm(DeviceParameters deviceParameters, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!isSydwLogin(request)) {
            return "modules/sys/sysLogin";
        }
        model.addAttribute("deviceParameters", deviceParametersService.get(deviceParameters.getTzsbbh()));
        return "zhuoyue/sydw/deviceParametersForm";
    }

    @RequestMapping(value = "deviceDetail")
    public String deviceDetail(DeviceParameters deviceParameters, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!isSydwLogin(request)) {
            return "modules/sys/sysLogin";
        }
        model.addAttribute("deviceParameters", deviceParametersService.get(deviceParameters.getTzsbbh()));
        return "zhuoyue/sydw/deviceParametersDetail";
    }

    @RequestMapping(value = "mainList")
    public String mainList(MaintenanceRecordSz maintenanceRecordSz, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!isSydwLogin(request)) {
            return "modules/sys/sysLogin";
        }
        Page<MaintenanceRecordSz> page = maintenanceRecordSzService.findPage(new Page<MaintenanceRecordSz>(request, response), maintenanceRecordSz);
        model.addAttribute("page", page);
        return "zhuoyue/sydw/maintenanceRecordSzList";
    }

    @RequestMapping(value = "mainForm")
    public String mainForm(MaintenanceRecordSz mMaintenanceRecordSz, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!isSydwLogin(request)) {
            return "modules/sys/sysLogin";
        }
        // 故障状态
        MaintenanceRecordSz maintenanceRecordSz = maintenanceRecordSzService.get(mMaintenanceRecordSz.getRecordId());

        model.addAttribute("allFailureStatus", DictUtils.getDictList("FAILURE_STATUS"));
        String failureStatus = maintenanceRecordSz.getFailurePhenomenon();

        List failureStatusList = new ArrayList();
        if (StringUtils.isNotEmpty(failureStatus)) {
            String[] failureStatusArray = failureStatus.split(",");
            for (int i = 0; i < failureStatusArray.length; i++) {
                failureStatusList.add(failureStatusArray[i]);
            }
        }
        maintenanceRecordSz.setFailureStatusList(failureStatusList);

        model.addAttribute("maintenanceRecordSz", maintenanceRecordSz);

        return "zhuoyue/sydw/maintenanceRecordSzForm";
    }

    @RequestMapping(value = "mainPrint")
    public void mainPrint(MaintenanceRecordSz maintenanceRecordSz, HttpServletRequest request, HttpServletResponse response, Model model) throws IOException {
        DataSource dataSource = SpringContextHolder.getBean(DataSource.class);

        String fileName = "report/wbmainreport/wb_zb.jasper";

        ServletOutputStream ouputStream = null;
        InputStream is = null;
        byte[] bytes = null;
        try {
            Dict dict = dictService.findByIDValue(maintenanceRecordSz.getDeviceVariety());
            String deviceType = "1";
            if (dict != null) {
                deviceType = dict.getValue();
            }

            String dirc = request.getSession().getServletContext().getRealPath("/") + fileName.substring(0, fileName.lastIndexOf("/") + 1);
            String imgDirc = request.getSession().getServletContext().getRealPath("report/images/") + "\\";
            Map parameters = new HashMap();
            parameters.put("record_id", new Integer(maintenanceRecordSz.getRecordId()));
            parameters.put("DTTYPE", deviceType);
            parameters.put("SUBREPORT_DIR", dirc);
            parameters.put("IMAGES_DIR", imgDirc);
            is = request.getSession().getServletContext().getResourceAsStream("/" + fileName);
            bytes = JasperRunManager.runReportToPdf(is, parameters, dataSource.getConnection());

            response.setContentType("application/pdf");
            response.setContentLength(bytes.length);

            ouputStream = response.getOutputStream();
            ouputStream.write(bytes, 0, bytes.length);

            ouputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (ouputStream != null) {
                ouputStream.close();
            }
        }
    }

    @RequestMapping(value = "failureList")
    public String failureList(FailureReport failureReport, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!isSydwLogin(request)) {
            return "modules/sys/sysLogin";
        }
        Page<FailureReport> page = failureReportService.findPage(new Page<FailureReport>(request, response), failureReport);
        model.addAttribute("page", page);
        model.addAttribute("failureReport", failureReport);
        return "zhuoyue/sydw/failureReportList";
    }

    @RequestMapping(value = "failureForm")
    public String failureForm(FailureReport mFailureReport, HttpServletRequest request, HttpServletResponse response, Model model) {
        if (!isSydwLogin(request)) {
            return "modules/sys/sysLogin";
        }

        FailureReport failureReport = failureReportService.get(mFailureReport.getFormId());

        model.addAttribute("failureReport", failureReport);

        // 故障状态
        model.addAttribute("allFailureStatus", DictUtils.getDictList("FAILURE_STATUS"));

        // 处理状态
        model.addAttribute("allFailurePrecessStatus", DictUtils.getDictList("FAILURE_PROCESS_STATUS"));

        String failureStatus = failureReport.getFailureStatus();
        String processStatus = failureReport.getProcessStatus();

        List failureStatusList = new ArrayList();
        if (StringUtils.isNotEmpty(failureStatus)) {
            String[] failureStatusArray = failureStatus.split(",");
            for (int i = 0; i < failureStatusArray.length; i++) {
                failureStatusList.add(failureStatusArray[i]);
            }
        }
        failureReport.setFailureStatusList(failureStatusList);

        List processStatusList = new ArrayList();
        if (StringUtils.isNotEmpty(processStatus)) {
            String[] processStatusArray = processStatus.split(",");
            for (int i = 0; i < processStatusArray.length; i++) {
                processStatusList.add(processStatusArray[i]);
            }
        }
        failureReport.setProcessStatusList(processStatusList);

        return "zhuoyue/sydw/failureReportForm";
    }

    @RequestMapping(value = "inspectList")
    public String inspectList(WbInspectRecord wbInspectRecord, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<WbInspectRecord> page = wbInspectRecordService.findPage(new Page<WbInspectRecord>(request, response), wbInspectRecord);
        model.addAttribute("page", page);
        model.addAttribute("wbInspectRecord", wbInspectRecord);
        return "zhuoyue/sydw/wbInspectRecordList";
    }

    @RequestMapping(value = "inspectForm")
    public String inspectForm(WbInspectRecord mWbInspectRecord, Model model) {
        WbInspectRecord wbInspectRecord = wbInspectRecordService.get(mWbInspectRecord.getId());
        model.addAttribute("wbInspectRecord", wbInspectRecord);
        return "zhuoyue/sydw/wbInspectRecordForm";
    }

    @RequestMapping(value = "insuranceList")
    public String insuranceList(WbInsuranceRecord wbInsuranceRecord, HttpServletRequest request, HttpServletResponse response, Model model) {
        Page<WbInsuranceRecord> page = wbInsuranceRecordService.findPage(new Page<WbInsuranceRecord>(request, response), wbInsuranceRecord);
        model.addAttribute("page", page);
        model.addAttribute("wbInsuranceRecord", wbInsuranceRecord);
        return "zhuoyue/sydw/wbInsuranceRecordList";
    }

    @RequestMapping(value = "insuranceForm")
    public String insuranceForm(WbInsuranceRecord mWbInsuranceRecord, Model model) {
        WbInsuranceRecord wbInsuranceRecord = wbInsuranceRecordService.get(mWbInsuranceRecord.getId());
        model.addAttribute("wbInsuranceRecord", wbInsuranceRecord);
        return "zhuoyue/sydw/wbInsuranceRecordForm";
    }

    public boolean isSydwLogin(HttpServletRequest request) {
        GgSydw ggSydw = (GgSydw) request.getSession().getAttribute(GG_SYDW_SESSION);
        if (ggSydw == null) {
            return false;
        }
        return true;
    }
}